import React, {
	PureComponent
} from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, TreeSelect, Tree, message, Badge, Divider, Upload, Radio, label, Table, Popconfirm } from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Role.less';
import { getusername } from '../../utils/utils';

//默认状态
var state;

/*角色*/
const { MonthPicker, RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Option } = Select;
const TreeNode = Tree.TreeNode;
const {
	TextArea
} = Input;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

//权限菜单 treeDtae
var treeData = []; //tree菜单内容
var Keysarry = ""; //权限配置获取选中项的值
var checkkey = []; //权限配置默认选中项的值

//机构管理
var treeorgData = []; //tree菜单内容
var Keysorgarry = ""; //权限配置获取选中项的值
var checkorgkey = ""; //权限配置默认选中项的值
console.log(getusername());


//人员查询
var table2 = [];
var table2col = [];
const columns2 = [{
	title: '组织结构编码',
	dataIndex: 'orgId',
	key: 'orgId',
}, {
	title: '员工名称',
	dataIndex: 'name',
	key: 'name',
}, {
	title: '所属学校',
	dataIndex: 'schoolName',
	key: 'schoolName',
}];
//table复选框选中
// rowSelection objects indicates the need for row selection
var rowSelections2 = "";
const rowSelection2 = {
	getCheckboxProps(record) {
		return {
			defaultChecked: record.isRole == 1, // 配置默认勾选的列
		};
	},
	onSelect: (record, selected, selectedRows) => {
		rowSelections2 = new Object(); //声明对象
		rowSelections2.selected = selected;
		rowSelections2.selectedRows = selectedRows;
	},
	onSelectAll: (selected, selectedRows, changeRows) => {
		rowSelections2 = new Object(); //声明对象
		rowSelections2.selected = selected;
		rowSelections2.selectedRows = selectedRows;
	},
};
const CreateForm = Form.create()(props => {
	const {
		modalVisible,
		form,
		handleAdd,
		handleModalVisible,
		title,
		obj,
		onCheck,
		renderTreeNodes,
		onChangetree
	} = props;
	const {
		getFieldDecorator
	} = form;
	const okHandle = () => {
		if(title == "新建" || title == "编辑") {
			form.validateFields((err, fieldsValue) => {
				if(err) return;
				form.resetFields();
				if(fieldsValue.state == undefined) {
					fieldsValue.state = 1
				};
				if(fieldsValue.description == undefined) {
					fieldsValue.description = ""
				};
				handleAdd(title, obj.roleId, fieldsValue);
			});
		} else {
			form.validateFields((err, fieldsValue) => {
				form.resetFields();
				handleAdd(title, obj.roleId, fieldsValue);
			});
		}
	};
	
	if(title == "配置权限") {
		return(
			<Modal
     	maskClosable={false}
			destroyOnClose={true}
      width={'40%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    	<Form layout="horizontal">
           <FormItem label="权限"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('menuIds', {initialValue:obj,})(
           		<Tree checkable   multiple defaultCheckedKeys={checkkey}  onCheck={onCheck} selectable checkStrictly >
           		{renderTreeNodes(treeData)}
			</Tree>)}
          </FormItem>
    	</Form>
    </Modal>
		)
	} else if(title == "人员分配") {
		return(
			<Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
	>
		<TreeSelect	dropdownMatchSelectWidth	treeDefaultExpandAll	allowClear	dropdownStyle={{ maxHeight: 400, overflow: 'auto', }}  style={{ width: 300 }}    placeholder="请选择机构"
			treeData={treeorgData}   onChange={onChangetree} >
		</TreeSelect>	
		<Table  dataSource={table2} rowSelection={rowSelection2} columns={columns2}  size="small"/>
    </Modal>
		)
	} else {
		return(
			<Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    	<Form layout="horizontal">
          	<FormItem label="角色名称"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('name', {
	            	initialValue:obj.name,
	              	rules: [{ required: true, message: '角色名称不能为空!' }],
	            })(<Input />)}
	          </FormItem>
           	<FormItem label="状态"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('state', {
	            	initialValue:obj.state==undefined ? "1":obj.state,
	            })(<Select placeholder="请选择状态" allowClear>
                  	<Option value="1">有效</Option>
                  	<Option value="0">无效</Option>
                </Select>)}
          	</FormItem>
          	<FormItem label="角色描述"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('description',{
	            	initialValue:obj.description,
	            })(<TextArea rows={3} />)}
          </FormItem>
		</Form>
  	</Modal>
		);
	}
});



@connect(({ manarole, loading }) => ({
	manarole,
	loading: loading.models.manarole,
}))

@Form.create()
export default class TableList extends PureComponent {
	state = {
		modalVisible: false,
		expandForm: false,
		selectedRows: [],
		formValues: {},
		obj: "",
	};

	componentDidMount() {
		const { dispatch } = this.props;
		/*获取角色list*/
		dispatch({
			type: 'manarole/fetch_role',
			payload: {
				state :1,
			},
		});
		//角色-人员分配  查询机构
		dispatch({
			type: 'manarole/fetch_organ_tree',
			callback: (res, data) => {
				if(res == 1) {
					treeorgData = data;
				}
			},
		});
	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const {
			dispatch
		} = this.props;
		const {
			formValues
		} = this.state;
		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});
		const params = {
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			...formValues,
			...filters,
		};
		if(sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}
		dispatch({
			type: 'manarole/fetch_role',
			payload: params,
		});
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	onCheck = (checkedKeys) => {
		Keysarry = checkedKeys.checked;
	}
	//点击机构 查询用户
	onChangetree = (value) => {
		const {
			selectedRows
		} = this.state;
		this.props.dispatch({
			type: 'manarole/getEmployeeListByRole',
			payload: {
				roleId: selectedRows.map(row => row.roleId).join(','),
				orgId: value,
			},
			callback: (res, data) => {
				if(res == 1) {
					table2 = data;
				}
			},
		});
	}
	/*权限数据*/
	renderTreeNodes = (treeData) => {
		return treeData.map((item) => {
			if(item.children) {
				return(
					<TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
				);
			}
			return <TreeNode {...item} />;
		});
	}
	handleSearch = e => {
		e.preventDefault();
		const {
			dispatch,
			form
		} = this.props;
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			const values = { ...fieldsValue,
			};
			this.setState({
				formValues: values,
			});
			if(values.name == undefined) values.name = ""
			if(values.description == undefined) values.description = ""
			if(values.state == undefined) values.state = ""
			if(values.updatedAt == undefined) values.updatedAt = ""
			dispatch({
				type: 'manarole/fetch_role',
				payload: { ...values
				}
			});
		});
	};
	handleFormReset = () => {
		const {
			form,
			dispatch
		} = this.props;
		form.resetFields();
		this.setState({
			formValues: {},
		});
		dispatch({
			type: 'manarole/fetch_role',
		});
	}
	/*弹窗 */
	handleModalVisible = (flag, record, title) => {
		var obj = "";
		/*关闭弹窗-取消-colse*/
		if(flag == false) {
			this.setState({
				modalVisible: flag,
				title: title,
				obj: obj,
			});
		} else {
			/*操作关闭*/
			if(title == "新建") {
				this.setState({
					modalVisible: flag,
					title: title,
					obj: obj,
				});
			} else {
				const { selectedRows } = this.state;
				if((record == undefined || Object.keys(record).length == 0) && Object.keys(selectedRows).length == 0) {
					message.info("还未选择项");
				} else if(Object.keys(selectedRows).length > 1) {
					message.info("只能选择一项进行操作");
				} else {
					var Ids = [];
					if(record != undefined && Object.keys(record).length > 0) {
						Ids = record;
					} else if(selectedRows != null) {
						Ids.push(selectedRows.map(row => row.roleId).join(','));
					}
					if(title == "编辑") {
						selectedRows[0].state += '';
						this.setState({
							modalVisible: flag,
							title: title,
							obj: selectedRows[0],
						});
					} else if(title == "配置权限") {
						console.log(Ids);
						//默认查询tree
						this.props.dispatch({
							type: 'manarole/fetch_menu_checktree',
							payload: {
								roleId: Ids
							},
							callback: (res, data) => {
								treeData = [];
								treeData = data.selectTree;
								checkkey = [];
								
								for(var i = 0; i < data.selectMenuIds.length; i++) {
									checkkey.push(data.selectMenuIds[i]);
								}
								checkkey = data.selectMenuIds;
								console.log(checkkey);
								this.setState({
									modalVisible: flag,
									title: title,
									obj: checkkey,
								});
							}
						});
					} else if(title == "人员分配") {
						//默认查询所有人员
						this.props.dispatch({
							type: 'manarole/getEmployeeListByRole',
							payload: {
								roleId: Ids
							},
							callback: (res, data) => {
								table2 = [];
								table2 = data;
								this.setState({
									modalVisible: flag,
									title: title,
									obj: data,
								});
							}
						});
					}
				}
			}
		}
	};
	/*新增,修改*/
	handleAdd = (title, Id, fields) => {
		const {
			selectedRows
		} = this.state;
		if(title == "新建") {
			this.props.dispatch({
				type: 'manarole/add_role',
				payload: { ...fields,},
				callback: (res, resMsg) => {
					if(res == 1) {
						message.success(resMsg);
					} else {
						message.error(resMsg);
					}
				},
			});
		} else if(title == "编辑") {
			this.props.dispatch({
				type: 'manarole/edit_role',
				payload: {
					...fields,
					roleId: Id,
				},
				callback: (res, resMsg) => {
					if(res == 1) {
						message.success(resMsg);
					} else {
						message.error(resMsg);
					}
				},
			});
		} else if(title == "配置权限") {
			this.props.dispatch({
				type: 'manarole/insertRoleMenu',
				payload: {
					roleId: selectedRows.map(row => row.roleId).join(','),
					menuIds: Keysarry
				},
				callback: (res, resMsg) => {
					if(res == 1) {
						message.success(resMsg);
					} else {
						message.error(resMsg);
					}
				},
			});
		} else if(title == "人员分配") {
			var Id2 = [];
			if(rowSelections2.selected == true) { //人员id
				if(rowSelections2.selectedRows.length == 1) {
					Id2.push(rowSelections2.selectedRows[0].employeeId);
				} else {
					for(var i = 0; i < rowSelections2.selectedRows.length; i++) {
						Id2.push(rowSelections2.selectedRows[i].employeeId);
					}
				}
			}
			this.props.dispatch({
				type: 'manarole/fetch_org_userqx',
				payload: {
					roleId: selectedRows.map(row => row.roleId).join(','),
					employeeIds: Id2
				},
				callback: (res, resMsg) => {
					if(res == 1) {
						message.success(resMsg);
					} else {
						message.error(resMsg);
					}
					
				},
			});
		}
		console.log("关闭");
		this.setState({
			modalVisible: false,
		});
	};

	/*删除*/
	confirmModel = (title, Id) => {
		const { dispatch } = this.props;
		const { selectedRows } = this.state;
		if(Id == undefined && Object.keys(selectedRows).length == 0) {
			message.info("还未选择项");
		} else {
			var Ids = [];
			/*获取选中的用户名字*/
			var name =[];
			if(Id != undefined) {
				Ids = Id;
				name = Id;
			} else if(selectedRows != null) {
				Ids.push(selectedRows.map(row => row.roleId).join(','));
				name.push(selectedRows.map(row => row.name).join(','));
			}
			for(var i=0;i<name.length;i++){
				if(name[i] == getusername()){
					console.log("不能对自己进行操作");
				}
			}
			
			
			if(title == "删除") {
				Modal.confirm({
					title: '是否删除当前选中数据',
					content: '',
					onOk() {
						dispatch({
							type: 'manarole/remove_role',
							payload: {
								roleIds: Ids,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								} else {
									message.error(resMsg);
								}
							},
						});
					},
				});
			} else if(title == "启用" || title == "禁用") {
				var state;
				if(title == "启用") {
					state = 1;
				} else {
					state = 0;
				}
				Modal.confirm({
					title: '是否' + title + '当前数据选中',
					onOk() {
						dispatch({
							type: 'manarole/edit_role_state',
							payload: {
								roleIds: Ids,
								state: state,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								} else {
									message.error(resMsg);
								}
							},
						});
					},
				});
			}

		}
	}

	renderSimpleForm() {
		const {
			getFieldDecorator
		} = this.props.form;
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
      	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          	<Col md={8} sm={24}>
	            <FormItem label="角色名称">
	              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
	            </FormItem>
           	</Col>
           	<Col md={8} sm={24}>
	           	<FormItem label="描述">
			        {getFieldDecorator('description')(<Input placeholder="请输入" />)}
			    </FormItem>
		    </Col>
        	<Col md={8} sm={24}>
	            <FormItem label="状态">
	              {getFieldDecorator('state')(<Select  style={{ width: '100%' }} allowClear>
	                  <Option value="1">有效</Option>
	                  <Option value="0">无效</Option>
	                </Select>)}
	            </FormItem>
	        </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        	<Col md={24} sm={24}>
           	<span className={styles.submitButtons} style={{ float: 'right'}}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
		);
	}
	renderForm() {
		return this.state.expandForm = this.renderSimpleForm();
	}

	render() {
		const { manarole: { data }, loading } = this.props;
		const {
			selectedRows,
			modalVisible,
			title,
			obj
		} = this.state;
		/*const rowKey = function(record) {
		  return record.roleId;  //主键id
		};*/
		const columns = [{
			title: '序号',
			dataIndex: 'roleId',
			key: 'roleId',
			width: '10%',
			render: (text, record, index) => {
				return index + 1
			}
		}, {
			title: '角色名称',
			dataIndex: 'name',
			key: 'name',
			width: '30%',
		}, {
			title: '描述',
			dataIndex: 'description',
			key: 'description',
			width: '40%',
			render: (text) => <span className="coltdsn">{text}</span>,
		}, {
			title: '状态',
			dataIndex: 'state',
			key: 'state',
			width: '20%',
			render: (text, record, index) => {
				if(record.state == 1) {
					return "有效"
				} else if(record.state == 0) {
					return "无效"
				}
			}
		}];
		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible,
			confirmModel: this.confirmModel,
			renderTreeNodes: this.renderTreeNodes,
			onChangetree: this.onChangetree,
			onCheck: this.onCheck,
		};
		return(
			<PageHeaderLayout title="系统管理/角色管理">
      	<Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.submitButtons}>
            	<Button type="primary"  onClick={() => this.handleModalVisible(true,'','新建')}>新建</Button>
            	<Button type="primary"  onClick={() => this.handleModalVisible(true,'','编辑')}>编辑</Button>
              	{/*<Button type="primary"  onClick={() => this.confirmModel('删除')}>删除</Button>*/}
              	<Button  type="primary" onClick={() => this.confirmModel('启用')}>启用</Button>
		      	<Button  type="ghost"   onClick={() => this.confirmModel('禁用')}>禁用</Button>
		      	<Button  type="primary" onClick={() => this.handleModalVisible(true,'','配置权限')}>权限</Button>
		      	
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
      </Card>
      </PageHeaderLayout>
		);
	}
}